import type { ApiResponse } from '~/types/user'

export const useAvatarUpload = (refresh: () => Promise<void>) => {
  const avatarInput = ref<HTMLInputElement>()

  const triggerAvatarUpload = () => {
    avatarInput.value?.click()
  }

  const handleAvatarUpload = async (event: Event) => {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (!file) return

    const allowedTypes = ['image/jpeg', 'image/png']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('只支持 JPG 或 PNG 格式的图片')
      return
    }

    const maxSize = 5 * 1024 * 1024 // 5MB
    if (file.size > maxSize) {
      ElMessage.error('图片大小不能超过 5MB')
      return
    }

    try {
      const formData = new FormData()
      formData.append('file', file)
      const response = await customFetch<ApiResponse<string>>('/api/user/updateUserAvatar', {
        method: 'POST',
        body: formData,
        isLoading: false
      })

      if (response.data === 'success') {
        ElMessage.success('头像上传成功')
        await refresh()
      } else {
        ElMessage.error(response.data || '头像上传失败')
      }
    } catch (error) {
      ElMessage.error('头像上传失败')
    }
  }

  return {
    avatarInput,
    triggerAvatarUpload,
    handleAvatarUpload
  }
}
